import React, { Component, Suspense } from "react";
import { connect } from "dva";
import { Drawer, Form, Button, Col, Row, Input, Select, DatePicker, Icon, message, Pagination, Modal, Spin, Table, Switch, } from "antd";
import styles from "./typeNode.less";
import SimilarQuestion from "./similarQuestion";
import { node } from "prop-types";
import axios from "axios";
import UserSession from "@/UserSession";
import { userTypeList } from '@/services/geographic';
import { knowledgeAtlasNodeDetail } from "@/services/knowledgegraph";

const { Option } = Select;
const FormItem = Form.Item;
const { Search, TextArea } = Input;
class TypeNodeEdit extends Component {
	constructor(props) {
		super(props);
		this.state = {
			visible: false,
			node: {},
			similarQuestions: [],
			similarQuestion: "",
			childrenDrawer: false,
			classVisible: false,
			standardQus: "",
			classField: "q",
			linkTotal: 0,
			classPage: 1,
			relateList: [],
			relateQAs: [],
			searchClass: "",
			qaId: "",
			isNew: true,
			atlasExplain: "",
			atlasTitle: "",
			speechcraft: "",
			similarPage: 1,
			similarSearch: "",
			similarTotal: 0,
			allSimilarData: [],
			isSensitive: false,
			qaStatus: true,
			userTagList: [],
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
		if (this.props.visible) {
			this.setState({ visible: this.props.visible });
		}
		if (this.props.node) {
			this.setState({ node: this.props.node }, () => {
				if (this.props.node) {
					this.initKnow();
				}
			});
		}
	}

	componentWillReceiveProps(nextProps) {
		const { visible, node } = nextProps;
		if (nextProps.visible !== this.props.visible) {
			this.setState({ visible });
		}
		if (node) {
			this.setState({ node });
		}
	}

	initKnow = () => {
		this.setState({ isNew: false, }, () => {
			this.getNodeDetail();
			this.getUserTagList();
			// this.getAnswerDetailByQaid(qaId);
			// this.getQuestionsByQaid(qaId);
			// this.getStandardQuestionByQaId(qaId);
		});
	};

	/**
	 * 获取节点详情
	 */
	getNodeDetail = async () => {
		console.log(this.state.node);
		const { dispatch } = this.props;
		const { node } = this.state.node;
		if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeAtlasNodeDetail({ nodeId: node.id });
		} else {
			dispatch({
				type: "intentionsList/getNodeDetailByNodeId",
				payload: {
					id: node.id,
					urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
				},
				callback: (res) => {
					console.log(res);
				},
			});
		}
	};

	getAnswerDetailByQaid = (qaId) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getKnowledgeDetail",
				payload: { id: qaId },
				callback: (res) => {
					this.setState({
						atlasExplain: res.atlasExplain,
						atlasTitle: res.atlasTitle,
						relateList: !res.relateList === true ? [] : res.relateList,
						relateQAs: !res.relateList === true ? [] : res.relateQAs,
						speechcraft: res.speechcraft,
						isSensitive: res.isSensitive === 1 ? true : false,
						qaStatus: !res.disabled,
					});
				},
			});
		});
	};

	getQuestionsByQaid = (qaId, isTowDrawer) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getAlikeQuestionList",
				payload: {
					id: qaId,
					limit: 999999999,
					page: 1,
					search: this.state.similarSearch,
				},
				callback: (res) => {
					const arr = [];
					for (const i of res.list) {
						arr.push(i.question);
					}
					this.setState(
						{
							allSimilarData: arr,
							similarTotal: res.total,
						},
						() => {
							this.pageData();
						}
					);
				},
			});
		});
	};

	pageData = () => {
		const { similarTotal, similarPage, similarQuestions, allSimilarData, } = this.state;
		let minIndex = similarPage * 10 - 10;
		let maxIndex = similarPage * 10;
		let currenArr = [];
		let allData = allSimilarData;
		for (let i = minIndex; i < maxIndex; i++) {
			if (allData[i]) {
				currenArr.push(allData[i]);
			}
		}

		this.setState({
			similarQuestions: currenArr,
		});
	};

	getStandardQuestionByQaId = (qaId) => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getStandardQuestion",
				payload: { id: qaId },
				callback: (res) => {
					this.setState({
						standardQus: res.question,
					});
				},
			});
		});
	};

	getQaIdByReq = () => {
		const { dispatch } = this.props;
		const obj = {};
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "intentionsList/getQaId",
				payload: obj,
				callback: (res) => {
					this.setState({
						qaId: res.qaId,
					});
				},
			});
		});
	};

	showDrawer = () => {
		this.setState({
			visible: true,
		});
	};

	onClose = (title, qaId, type) => {
		const { isGuideOption } = this.props;
		this.setState(
			{
				visible: false,
			},
			() => {
				this.props.form.resetFields();
			}
		);
		if (this.props.close) {
			this.props.close(title ? title : "");
		}
	};
	addQuestion(data) {
		let similarArr = this.state.allSimilarData;
		similarArr.unshift(data);
		this.setState({ allSimilarData: similarArr });
		// let similarArr = this.state.similarQuestions
		// similarArr.unshift(data);
		// this.setState({ similarQuestions: similarArr })
	}

	fixQuestion = (e) => {
		this.setState({
			similarQuestion: e.target.value,
		});
	};

	remove(index, e) {
		let similarArr = this.state.allSimilarData;
		similarArr = similarArr.filter((key) => key !== e);
		this.setState({ allSimilarData: similarArr });
	}

	changeIndex(index) {
		let similarArr = this.state.allSimilarData;
		similarArr[index - 1] = similarArr.splice(
			index,
			1,
			similarArr[index - 1]
		)[0];
		this.setState({ allSimilarData: similarArr });
	}
	addIcon() {
		if (this.state.similarQuestion === "") {
			message.error("问题不可为空");
			return false;
		}
		let similarArr = this.state.similarQuestions;
		similarArr.unshift(this.state.similarQuestion);
		this.setState({
			similarQuestions: similarArr,
			similarQuestion: "",
		});
	}
	changeSimilarItem(data) {
		let index = data.index;
		let val = data.val;
		let similarArr = this.state.allSimilarData;
		similarArr[index] = val;
		if (this !== data) {
			this.setState({ allSimilarData: similarArr });
		}
	}
	saveNode() {
		const form = this.props.form;
		const { similarQuestions, node, relateQAs, qaId, isNew, allSimilarData, userTagList } = this.state;
		const { isGuideOption } = this.props;
		let that = this;
		form.validateFields((err, values) => {
			if (err) {
				return false;
			};
			let userTagIdList = [];
			if (values.userType && values.userType.length > 0) {
				userTagList.forEach(item => {
					if (values.userType.indexOf(item.id) > -1) {
						userTagIdList.push({ id: item.id, tagName: item.tagName });
					}
				})
			};
			if (isGuideOption) {
				let obj = {
					processName: values.title,
					id: node.id,
					processType: node.nodeType,
					questions: allSimilarData,
					explains: values.dis,
					userTagIdList,
				};
				const { dispatch, currentUser } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "intentionsList/editProcessGuide",
						payload: obj,
						callback: (res) => {
							if (typeof res.code !== 'undefined' && res.code !== 0) {
								// message["error"](`${res.message}`);
							} else {
								message.info(res.msg);
								this.onClose(values.title, qaId, 2);
							}
						},
					});
				});
			} else {
				// let questionList = allSimilarData;
				// questionList.unshift(values.ask);

				let questionList = [];
				questionList.push(values.ask);
				questionList = questionList.concat(allSimilarData);

				let obj = {
					answers: null,
					slots: null,
					slotAndApi: null,
					apiId: null,
					atlasId: node.atlas_id,
					atlasNodeId: node.id ? node.id : node._id,
					qaId,
					questions: questionList,
					atlasTitle: values.title,
					atlasExplain: values.dis,
					atlasKnowledgeType: 3,
					isNew,
					isSharedQA: false,
					categoryId: "/",
					isForever: true,
					relateQAs: relateQAs,
					speechcraft: values.talk,
					disabled: !this.state.qaStatus,
					isSensitive: this.state.isSensitive ? 1 : 0,
					userTagIdList,
				};

				const { dispatch, currentUser } = that.props;
				that.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "intentionsList/saveQA",
						payload: obj,
						callback: (res) => {
							if (typeof res.code !== 'undefined' && res.code !== 0) {
								// message["error"](`${res.message}`);
							} else {
								message.info(res.msg);
								this.props.close(values.title, res.data, this.props.node.newType);
							}
						},
					});
				});
			}
		});
	}
	onChildrenDrawerClose = () => {
		this.setState({ allSimilarData: this.SimilarQuestion.state.moreQuestionList }, () => {
			this.setState({ childrenDrawer: false });
		});
	};
	showChildrenDrawer = () => {
		// const { qaId } = this.props;
		this.setState({
			childrenDrawer: true,
			isShowSimTitle: false,
			drawerLoading: false,
			isTowDrawer: true,
		});
		// if (qaId) {
		//   this.getQuestionsByQaid(qaId, true);
		//   this.getStandardQuestionByQaId(qaId);
		// }
	};
	// onCloseChildren() {
	//   this.setState({ childrenDrawer: false });
	// }

	//关联问题  ---开始
	addLinkQa = () => {
		this.setState({ classVisible: true });
		this.fetchLinkData();
	};
	fetchLinkData = () => {
		this.setState({ loading: true, }, () => {
			const { dispatch, currentUser } = this.props;
			this.reqRef = requestAnimationFrame(() => {
				dispatch({
					type: "intentionsList/linkBoxJson",
					payload: {
						robotId: currentUser.robotId,
						question: this.state.standardQus,
						field: this.state.classField,
						query: this.state.searchClass,
						page: this.state.classPage,
						limit: 10,
					},
					callback: (res) => {
						const arr = res.qaList;
						const suggestionsLength = res.suggestList.length;
						this.setState({
							linkTotal: res.total,
							linkData: arr,
							loading: false,
							suggestionsLength,
						});
					},
				});
			});
		});
	};
	classHandleCancel = () => {
		this.setState({
			classVisible: false,
			searchClass: "",
		});
	};
	classSelectChange = (e) => {
		this.setState({ classField: e, classPage: 1, }, () => {
			this.fetchLinkData();
		});
	};
	fanye = (e, a) => {
		this.setState({ classPage: e, }, () => {
			return this.fetchLinkData();
		});
	};
	searchClass = (e) => {
		this.setState({ searchClass: e, classPage: 1, }, () => {
			this.fetchLinkData();
		});
	};
	addLinkThis = (item) => {
		let arr = [];
		let relateArr = [];
		arr = arr.concat(this.state.relateQAs);
		if (arr.length >= 10) {
			return message.error("关联问最多添加10条");
		};
		arr.unshift(item.sid);
		relateArr = relateArr.concat(this.state.relateList);
		relateArr.unshift(item);
		this.setState({ relateQAs: arr, relateList: relateArr });
	};

	onDelRelateQa = (index, qa) => {
		const arr = this.state.relateList;
		const { relateQAs } = this.state;
		for (let i = 0; i < relateQAs.length; i++) {
			if (relateQAs[i] === qa.id) {
				relateQAs.splice(i, 1);
			}
		};
		arr.splice(index, 1);
		this.setState({ relateList: arr, relateQAs });
	};
	onSetRelateQa = (index) => {
		const arr = this.state.relateList;
		if (index !== 0) {
			arr[index] = arr.splice(index - 1, 1, arr[index])[0];
		} else {
			arr.push(arr.shift());
		};
		this.setState({ relateList: arr });
	};
	// 关联问题 ---结束
	setNode = (data) => {
		let that = this;
		that.setState(
			{
				atlasExplain: "",
				allSimilarData: [],
				similarTotal: 0,
			},
			() => {
				if (data) {
					that.setState(
						{
							atlasExplain: data.explains,
							allSimilarData: data.questions,
							similarTotal: data.questions.length,
							// similarQuestions:data.question[1].similarQuestions
						},
						() => {
							that.pageData();
						}
					);
				}
			}
		);
	};

	//敏感/非敏感
	onChangeSensitive = (value) => {
		this.setState({ isSensitive: value });
	};

	//启用/禁用
	onChangeQaStatus = (value) => {
		this.setState({ qaStatus: value });
	};

	/* 获取用户类型-筛选框 */
	getUserTagList = async () => {
		const res = await userTypeList({ current: 1, size: 999999 });
		this.setState({ userTagList: res.records ? res.records : [], });
	};

	render() {
		const { getFieldDecorator } = this.props.form;
		const { node, similarQuestions, similarQuestion, allSimilarData, userTagList, } = this.state;
		const { isGuideOption } = this.props;
		const formItemLayout = {
			labelCol: {
				xs: { span: 26 },
				sm: { span: 4 },
			},
			wrapperCol: {
				xs: { span: 22 },
				sm: { span: 20 },
			},
		};
		const formItemLayoutWithOutLabel = {
			wrapperCol: {
				xs: { span: 22, offset: 4 },
				sm: { span: 20, offset: 4 },
			},
		};
		this.columns = [
			{
				title: "问题",
				key: "question",
				dataIndex: "question",
			},
			{
				title: "分类",
				key: "category",
				dataIndex: "category",
			},
			{
				title: "操作",
				render: (text, item) => {
					return (
						<div>
							{this.state.relateQAs.indexOf(item.sid) === -1 ? (
								<Button type='primary' size='small' onClick={() => this.addLinkThis(item)} icon='link'>关联</Button>
							) : (
								<Button htmlType='button' size='small' icon='link'>已关联</Button>
							)}
						</div>
					);
				},
			},
		];
		return (
			<div>
				<Drawer
					title={node.label ? node.label : node.name}
					width={680}
					onClose={() => this.onClose("")}
					visible={this.state.visible}
					bodyStyle={{ paddingBottom: 80 }}
				>
					<Form>
						{isGuideOption ? (
							<div>
								<Form.Item label='选项' {...formItemLayout}>
									{getFieldDecorator("title", {
										initialValue: node.label,
										rules: [{ required: true, message: "选项不能为空" }],
									})(
										<Input
											style={{ width: "88%" }}
											placeholder='选项'
											className={styles.inputItem}
											disabled={!UserSession.isSystemKnowledge() ? false : true}
										/>
									)}
								</Form.Item>
								<Form.Item label='说明' {...formItemLayout}>
									{getFieldDecorator("dis", {
										initialValue: this.state.atlasExplain
											? this.state.atlasExplain
											: "",
									})(
										<TextArea
											style={{ width: "88%" }}
											placeholder='说明'
											className={styles.inputItem}
											disabled={!UserSession.isSystemKnowledge() ? false : true}
										/>
									)}
								</Form.Item>
							</div>
						) : (
							<div>
								<div className={styles.label}>基础设置</div>
								<Form.Item label='标题' {...formItemLayout}>
									{getFieldDecorator("title", {
										initialValue: node.name,
										rules: [{ required: true, message: "标题不能为空" }],
									})(
										<Input
											style={{ width: "88%" }}
											placeholder='标题'
											className={styles.inputItem}
											disabled={!UserSession.isSystemKnowledge() ? false : true}
										/>
									)}
								</Form.Item>
								<Form.Item label='说明' {...formItemLayout}>
									{getFieldDecorator("dis", {
										initialValue: this.state.atlasExplain
											? this.state.atlasExplain
											: "",
									})(
										<TextArea
											style={{ width: "88%" }}
											placeholder='说明'
											className={styles.inputItem}
											disabled={!UserSession.isSystemKnowledge() ? false : true}
										/>
									)}
								</Form.Item>
								<Form.Item label='引导话术' {...formItemLayout}>
									{getFieldDecorator("talk", {
										initialValue: this.state.speechcraft
											? this.state.speechcraft
											: "",
									})(
										<TextArea
											style={{ width: "88%" }}
											placeholder='引导话术'
											className={styles.inputItem}
											disabled={!UserSession.isSystemKnowledge() ? false : true}
										/>
									)}
								</Form.Item>
								{UserSession.isSystemDataKnowledge() ? null : (
									<Form.Item label='是否启用' {...formItemLayout}>
										{getFieldDecorator("qaStatus", {
											initialValue: this.state.qaStatus
												? this.state.qaStatus
												: undefined,
										})(
											<Switch
												checkedChildren='启用'
												unCheckedChildren='禁用'
												checked={this.state.qaStatus}
												onChange={this.onChangeQaStatus}
											/>
										)}
									</Form.Item>
								)}
								{/* <Form.Item label='敏感状态' {...formItemLayout}>
									{getFieldDecorator("isSensitive", {
										initialValue: this.state.isSensitive
											? this.state.isSensitive
											: false,
									})(
										<Switch
											checkedChildren='敏感'
											unCheckedChildren='非敏感'
											checked={this.state.isSensitive}
											onChange={this.onChangeSensitive}
										/>
									)}
								</Form.Item> */}
								{!UserSession.isAdmin() && !UserSession.isSystemKnowledge() ? (
									<Form.Item label='适用标签' {...formItemLayout}>
										{getFieldDecorator("userType", {
											valuePropName: "checked",
										})(
											<Select mode="multiple">
												{userTagList && userTagList.length > 0 ? (
													userTagList.map(item => {
														return <Select.Option value={item.id} key={item.id} item={item}>{item.tagName}</Select.Option>
													})
												) : null}
											</Select>
										)}
									</Form.Item>
								) : ('')}
								<Row
									style={{
										borderTop: "1px solid #cacaca",
										marginBottom: "24px",
									}}></Row>
								<div className={styles.label}>问题</div>
								<Form.Item label='标准问' {...formItemLayout}>
									{getFieldDecorator("ask", {
										initialValue: this.state.standardQus
											? this.state.standardQus
											: "",
										rules: [{ required: true, message: "标准问必填" }],
									})(
										<Input
											style={{ width: "88%" }}
											placeholder='请添加标准问'
											className={styles.inputItem}
											disabled={!UserSession.isSystemKnowledge() ? false : true}
										/>
									)}
								</Form.Item>
							</div>
						)}

						<SimilarQuestion
							onRef={(ref) => {
								this.SimilarQuestion = ref;
							}}
							keys={1}
							seeMore={() => this.showChildrenDrawer()}
							isShowMore={allSimilarData.length > 6}
							similarQuestions={allSimilarData}
							addQuestion={this.addQuestion.bind(this)}
							remove={this.remove.bind(this)}
							changeIndex={this.changeIndex.bind(this)}
							changeSimilarItem={this.changeSimilarItem.bind(this)}
							isGuid={isGuideOption}
						/>

						{isGuideOption ? (
							""
						) : (
							<div>
								<Row style={{ margin: "10px 0px" }}>
									<Col span={4}>
										<div className={styles.label}>关联问题</div>
									</Col>
									<Col span={2} offset={16}>
										<div>
											<Button
												htmlType='button'
												// disabled={this.state.synchronous && this.state.shared}
												style={{ marginLeft: 10 }}
												type='primary'
												size='small'
												onClick={() => this.addLinkQa()}>
												添加关联知识点
											</Button>
										</div>
									</Col>
								</Row>
								{this.state.relateList.map((qa, qaIndex) => {
									return (
										<Form.Item {...formItemLayoutWithOutLabel} key={qaIndex}>
											<div style={{ position: 'relative' }}>
												{item.relateType === 1 ? (
													<span style={{
														background: '#f5f5f5',
														padding: '1px 7px',
														borderRadius: '5px',
													}}>问答</span>
												) : item.relateType === 2 ? (
													<span style={{
														background: '#f5f5f5',
														padding: '1px 7px',
														borderRadius: '5px',
													}}>导图</span>
												) : item.relateType === 3 ? (
													<span style={{
														background: '#f5f5f5',
														padding: '1px 7px',
														borderRadius: '5px',
													}}>多轮</span>
												) : null}
												<Input
													value={qa.question}
													key={qaIndex}
													disabled
													style={{ width: "88%", paddingRight: 60 }}
												/>
												{UserSession.isSystemKnowledge() ? null : (
													<span>
														<Icon
															className='dynamic-delete-button'
															type='close-circle'
															onClick={() => this.onDelRelateQa(qaIndex, qa)}
															style={{
																fontSize: 20,
																marginLeft: 10,
																cursor: "pointer",
																marginTop: 5,
															}}
														/>
														{qaIndex > 0 ? (
															<Icon
																type='arrow-up'
																onClick={() => this.onSetRelateQa(qaIndex)}
																style={{
																	fontSize: 20,
																	marginLeft: 10,
																	cursor: "pointer",
																	marginTop: 5,
																}}
															/>
														) : (
															""
														)}
													</span>
												)}
											</div>
										</Form.Item>
									);
								})}
							</div>
						)}
						<Drawer
							title='返回'
							width={720}
							onClose={this.onChildrenDrawerClose}
							visible={this.state.childrenDrawer}
							bodyStyle={{ paddingBottom: 80 }}
							destroyOnClose>
							<SimilarQuestion
								onRef={(ref) => {
									this.SimilarQuestion = ref;
								}}
								isShowMore={false}
								isTowDrawer={this.state.isTowDrawer}
								similarQuestions={allSimilarData}
								addQuestion={this.addQuestion.bind(this)}
								remove={this.remove.bind(this)}
								changeIndex={this.changeIndex.bind(this)}
								changeSimilarItem={this.changeSimilarItem.bind(this)}
								isGuid={isGuideOption}
							/>
						</Drawer>
					</Form>
					<div
						style={{
							position: "absolute",
							right: 0,
							bottom: 0,
							width: "100%",
							borderTop: "1px solid #e9e9e9",
							padding: "10px 16px",
							background: "#fff",
							textAlign: "right",
						}}>
						<Button onClick={this.onClose} style={{ marginRight: 8 }}>
							取消
						</Button>
						<Button onClick={this.saveNode.bind(this)} type='primary'>
							保存
						</Button>

						<Modal
							visible={this.state.classVisible}
							title='选择关联问题'
							onCancel={this.classHandleCancel}
							footer={[]}
							width={750}
							key='2'
							centered>
							<Form layout='inline' style={{ paddingBottom: 20 }}>
								<FormItem>
									<Select
										style={{ width: 160 }}
										defaultValue={this.state.classField}
										onChange={this.classSelectChange}>
										<Option value='q'>搜索问题</Option>
										<Option value='a'>搜索答案</Option>
									</Select>
								</FormItem>
								<FormItem>
									<Search
										placeholder='请输入内容'
										onSearch={(value) => this.searchClass(value)}
										style={{ width: 320 }}
										allowClear
									/>
								</FormItem>
							</Form>
							<Spin spinning={this.state.loading}>
								<Table
									style={{ height: 500, overflow: "auto" }}
									size='small'
									columns={this.columns}
									dataSource={this.state.linkData} // 数据
									rowKey='sid'
									pagination={{
										// 分页
										total: parseInt(this.state.linkTotal), // 数据总数量
										pageSize: 10,
										onChange: (e) => this.fanye(e),
										showQuickJumper: true,
									}}
								/>
							</Spin>
						</Modal>
					</div>
				</Drawer>
			</div>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(TypeNodeEdit));
